package com.yonyou.brigade.order_center.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.model.Developer;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IBriSysConfigService;
import com.yonyou.brigade.basic_init.service.IDeveloperService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.dao.BriOrderListMapper;
import com.yonyou.brigade.order_center.model.*;
import com.yonyou.brigade.order_center.service.*;
import com.yonyou.brigade.order_center.util.ImportExcel;
import com.yonyou.brigade.order_center.util.OrderCenterConvert;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.framework.thread.ThreadPoolExecutorFactory;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import net.sf.json.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Time;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.yonyou.brigade.util.resultutil.HttpSendUtils.sendPost;

@Service
public class BriOrderServiceImpl implements IBriOrderService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public final static String DD_DATE_FORMAT = "yyyy-MM-dd";

    @Autowired
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briHotelRoomServiceImpl")
    private IBriHotelRoomService briHotelRoomService;

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    @Qualifier("briFlightInfoServiceImpl")
    private IBriFlightInfoService briFlightInfoService;

    @Autowired
    @Qualifier("briFlightPassengerServiceImpl")
    private IBriFlightPassengerService briFlightPassengerService;

    @Autowired
    @Qualifier("briFlightOrderContactServiceImpl")
    private IBriFlightOrderContactService briFlightOrderContactService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("briTrainPassengerServiceImpl")
    private IBriTrainPassengerService briTrainPassengerService;

    @Autowired
    @Qualifier("briTrainTicketServiceImpl")
    private IBriTrainTicketService briTrainTicketService;

    @Autowired
    @Qualifier("briTrainPaymentServiceImpl")
    private IBriTrainPaymentService briTrainPaymentService;

    @Autowired
    @Qualifier("briCarOrderServiceImpl")
    private IBriCarOrderService briCarOrderService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    private BriOrderListMapper briOrderListMapper;

    @Autowired
    private IBriSysConfigService briSysConfigService;

    @Autowired
    private IMailService mailService;

    @Autowired
    private IDeveloperService developerService;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Value("${ybz.matchApply4processes.url}")
    private String URL;

    @Value("${brigade.cur}")
    private String curEnv;

    @Value("${brigade.url.projecturl}")
    private String projecturl;

    @Value("${note.push.orders}")
    private String notePushOrders;


    @Autowired
    private IInvoiceRelationshipService relationshipService;

    @Autowired
    private IExpenseStatusService expenseStatusService;

    public void updateOrderBxState(List<String> notePk, int state) {

    }

    @Override
    public List<BriOrderListVO> getOrdersByOrderNoAndClass(JSONArray params) {
        List<BriOrderListVO> briOrderListVOS = new CopyOnWriteArrayList<>();
        List<BriOrderListDTO> briOrderListDTOS = new CopyOnWriteArrayList<>();
        if (!CollectionUtils.isEmpty(params)) {
            List<String> flightOrderNos = new CopyOnWriteArrayList<>();
            List<String> trainOrderNos = new CopyOnWriteArrayList<>();
            List<String> hotelOrderNos = new CopyOnWriteArrayList<>();
            List<String> carOrderNos = new CopyOnWriteArrayList<>();
            for (Object param : params) {
                JSONObject paramJSON = JSONObject.parseObject(JSON.toJSONString(param));
                if (CnvFlightOrderDO.FLIGHT.equals(paramJSON.getString("orderClassification"))) {
                    flightOrderNos.add(paramJSON.getString("orderNo"));
                } else if (CnvTrainOrderDO.TRAIN.equals(paramJSON.getString("orderClassification"))) {
                    trainOrderNos.add(paramJSON.getString("orderNo"));
                } else if (CnvHotelOrderDO.HOTEL.equals(paramJSON.getString("orderClassification"))) {
                    hotelOrderNos.add(paramJSON.getString("orderNo"));
                } else if (CnvCarOrderDO.CAR.equals(paramJSON.getString("orderClassification"))) {
                    carOrderNos.add(paramJSON.getString("orderNo"));
                }
            }
            if (!CollectionUtils.isEmpty(flightOrderNos)) {
                List<BriOrderListDTO> briFlightOrderListDTOS = briOrderListMapper.getFlightOrdersByOrderNos(flightOrderNos);
                if (!CollectionUtils.isEmpty(briFlightOrderListDTOS)) {
                    briOrderListDTOS.addAll(briFlightOrderListDTOS);
                }
            }
            if (!CollectionUtils.isEmpty(trainOrderNos)) {
                List<BriOrderListDTO> briTrainOrderListDTOS = briOrderListMapper.getTrainOrdersByOrderNos(trainOrderNos);
                if (!CollectionUtils.isEmpty(briTrainOrderListDTOS)) {
                    briOrderListDTOS.addAll(briTrainOrderListDTOS);;
                }
            }
            if (!CollectionUtils.isEmpty(hotelOrderNos)) {
                List<BriOrderListDTO> briHotelOrderListDTOS = briOrderListMapper.getHoteltOrdersByOrderNos(hotelOrderNos);
                if (!CollectionUtils.isEmpty(briHotelOrderListDTOS)) {
                    briOrderListDTOS.addAll(briHotelOrderListDTOS);
                }
            }
            if (!CollectionUtils.isEmpty(carOrderNos)) {
                List<BriOrderListDTO> briCarOrderListDTOS = briOrderListMapper.getCarOrdersByOrderNos(carOrderNos);
                if (!CollectionUtils.isEmpty(briCarOrderListDTOS)) {
                    briOrderListDTOS.addAll(briCarOrderListDTOS);
                }
            }
            if (!CollectionUtils.isEmpty(briOrderListDTOS)) {
                convertDTO2VO(briOrderListVOS, briOrderListDTOS, null);
            }
        }
        return briOrderListVOS;
    }

    /**
     * 获取个人订单列表
     * @param params
     * @return
     */
    @Override
    public List<BriOrderListVO> getBriOrderList(Map<String, Object> params) {
        int pageSize = params.get("pageSize") == null ? 10 :Integer.valueOf(String.valueOf(params.get("pageSize")));
        int pageNo = params.get("pageNo") == null ? 0 : (Integer.valueOf(String.valueOf(params.get("pageNo"))) - 1) * pageSize;
        params.put("pageSize", pageSize);
        params.put("pageNo", pageNo);
        String tenantId = String.valueOf(params.get("tenantId"));
        String orgPk = String.valueOf(params.get("orgPk"));
        JSONObject orderClassificationAllowExpenseByChannel = new JSONObject();
        List<BriChannel> enableChannelByTenant = briChannelService.getEnableChannelByTenant(tenantId);
        if (!CollectionUtils.isEmpty(enableChannelByTenant)) {
            for (BriChannel briChannel : enableChannelByTenant) {
                orderClassificationAllowExpenseByChannel.put(briChannel.getChannel().concat("_Prepay_").concat(String.valueOf(briChannel.getId())), briChannel.getReimbursementPayByEnterprise());
                orderClassificationAllowExpenseByChannel.put(briChannel.getChannel().concat("_Selfpay_").concat(String.valueOf(briChannel.getId())), briChannel.getReimbursementPayBySelf());
            }
        }
        String hasTravelled = String.valueOf(params.get("hasTravelled"));
        List<BriOrderListVO> briOrderListVOS = new CopyOnWriteArrayList<>();
        Map<String, List<Map<String, String>>> canBeSeen = assembleCanBeSeen(orderClassificationAllowExpenseByChannel);
        params.put("canBeSeen", canBeSeen);
        /*
        add by yangxw1 2021年12月9日 浙江国贸 在报销单填单的时候，选择了申请单，就用申请单单号去数据库查询携程订单
         */
        if(params.containsKey("billdno")){
            List<String> billno = new ArrayList<>();
            billno.add(String.valueOf(params.get("billdno")));
            params.put("billno", billno);
        }else{
            params.put("billno",null);
        }
        List<BriOrderListDTO> briOrderListDTOS = null;
        try {
            briOrderListDTOS=  briOrderListMapper.selectOrderList(params);
        } catch (Exception e) {
            logger.error("商旅本地查询发生异常："+e.getMessage()+e.getStackTrace());
//            briOrderListDTOS = selectNCCOrderList(params);
        }
        //modify by yangxw1 2021年6月15日 从NCC获取订单列表
//        List<BriOrderListDTO> briOrderListDTOS = selectNCCOrderList(params);
        logger.error("briOrderListDTOS:"+briOrderListDTOS.toString());
        if (!CollectionUtils.isEmpty(briOrderListDTOS)) {
            convertDTO2VO(briOrderListVOS, briOrderListDTOS, orderClassificationAllowExpenseByChannel);
            if (!StringUtils.isEmpty(hasTravelled) || !"null".equals(hasTravelled)) {
                List<BriOrderListVO> briOrderListVOSNotTravelled = new CopyOnWriteArrayList<>();
                List<BriOrderListVO> briOrderListVOSHasTravelled = new CopyOnWriteArrayList<>();
                for (BriOrderListVO briOrderListVO : briOrderListVOS) {
                    if ("0".equals(briOrderListVO.getHasTravelled())) {
                        briOrderListVOSNotTravelled.add(briOrderListVO);
                    } else if ("1".equals(briOrderListVO.getHasTravelled())){
                        briOrderListVOSHasTravelled.add(briOrderListVO);
                    }
                }
                if ("1".equals(hasTravelled)) {
                    // 已出行
                    return briOrderListVOSHasTravelled;
                } else if ("0".equals(hasTravelled)) {
                    // 未出行
                    return briOrderListVOSNotTravelled;
                }
            }
        }
        return briOrderListVOS;
    }

//    /**
//     *
//     * 查询NCC订单列表
//     * add by yangxw1 2021年6月15日
//     *
//     * @param params
//     * @return
//     */
//    private List<BriOrderListDTO> selectNCCOrderList(Map<String, Object> params){
//        List<BriOrderListDTO> BriOrderList = new ArrayList<BriOrderListDTO>();
//        String userId = String.valueOf( params.get("userId"));
//        String tenantId = String.valueOf(params.get("tenantId"));
//        List<String> userIdList = new ArrayList<String >();
//        userIdList.add(userId);
//
//        logger.error("selectNCCOrderList:-----params:"+params.toString());
//        logger.error("userIdList:"+userIdList.toString()+"tenantId:"+tenantId);
//        List<UcUserDto> userlist = userCenterService.getCompleteUcUserDtoByUserid(userIdList,tenantId);
//        logger.error("userlist:"+userlist.toString());
//        String userCode = userlist.get(0).getUserCode();
//
//        JSONObject paeam = new JSONObject();
//
//        JSONObject paeamOBJ = new JSONObject();
//
//        paeamOBJ.put("type",params.get("type") == null ? "":params.get("type"));
//        paeamOBJ.put("travelDateBegin",params.get("travelDateBegin") == null ? "":params.get("travelDateBegin"));
//        paeamOBJ.put("travelDateEnd",params.get("travelDateEnd") == null ? "":params.get("travelDateEnd"));
//        paeamOBJ.put("orderDateEnd",params.get("orderDateEnd") == null ? "":params.get("orderDateEnd"));
//        paeamOBJ.put("orderStatus",params.get("orderStatus") == null ? "":params.get("orderStatus"));
//        paeamOBJ.put("bxState",params.get("bxState") == null ? "":params.get("bxState"));
//        paeamOBJ.put("hasTravelled",params.get("hasTravelled") == null ? "":params.get("hasTravelled"));
//        paeamOBJ.put("searchInfo",params.get("searchInfo") == null ? "":params.get("searchInfo"));
//        paeamOBJ.put("pageSize",params.get("pageSize") == null ? "":params.get("pageSize"));
//        paeamOBJ.put("pageNo",params.get("pageNo") == null ? "":(Integer.valueOf(String.valueOf(params.get("pageNo")))/Integer.valueOf(String.valueOf(params.get("pageSize"))))+1);
//        //暂时注释掉这个查询条件
////        paeamOBJ.put("orderDateBegin",params.get("orderDateBegin") == null ? "":params.get("orderDateBegin"));
//        paeamOBJ.put("orderDateBegin","");
//        paeamOBJ.put("userCode",userCode);
//        paeam.put("paeamOBJ",paeamOBJ);
//        paeam.put("urlKey","/brigade/queryOrderList");
//        //POST=到NCC进行穿透
//        String url = ybzBaseUrl+"/open/brigade/nodeRef/toNCC";
//        logger.error("友报账进行地址穿透--url:"+url+" paeam:"+paeam.toString());
//        String NCCBriOrderListDTO = sendPost(url, paeam.toString());
//        logger.error("NCC返回数据NCCBriOrderListDTO"+NCCBriOrderListDTO);
//        if(!StringUtils.isEmpty(NCCBriOrderListDTO)){
//            JSONObject sonobj =  JSONObject.parseObject(NCCBriOrderListDTO);
//            String code = sonobj.getString("code");
//            if(!StringUtils.isEmpty(sonobj)  && "0000".equals(code)){
//                String datas = sonobj.getJSONArray("datas").toJSONString();
//                BriOrderList = JSONObject.parseArray(datas,BriOrderListDTO.class);
//            }
//        }
//
//        return BriOrderList;
//    }


    private Map<String, List<Map<String, String>>> assembleCanBeSeen(JSONObject orderClassificationAllowExpenseByChannel) {
        Set<String> fromTypeKeys = orderClassificationAllowExpenseByChannel.keySet();
        Map<String, List<Map<String, String>>> canBeSeen = new ConcurrentHashMap<>();
        List<Map<String, String>> listFlight = new CopyOnWriteArrayList<>();
        List<Map<String, String>> listHotel = new CopyOnWriteArrayList<>();
        List<Map<String, String>> listTrain = new CopyOnWriteArrayList<>();
        List<Map<String, String>> listCar = new CopyOnWriteArrayList<>();
        if (!CollectionUtils.isEmpty(fromTypeKeys)) {
            for (String fromTypeKey : fromTypeKeys) {
                List<String> orderClassificationList = StringUtils.isEmpty(orderClassificationAllowExpenseByChannel.getString(fromTypeKey)) ?
                        new ArrayList() : JSON.parseObject(orderClassificationAllowExpenseByChannel.getString(fromTypeKey), List.class);
                if (!CollectionUtils.isEmpty(orderClassificationList)) {
                    if (orderClassificationList.contains(CnvFlightOrderDO.FLIGHT)) {
                        assembleParam4List(listFlight, fromTypeKey);
                    }
                    if (orderClassificationList.contains(CnvHotelOrderDO.HOTEL)) {
                        assembleParam4List(listHotel, fromTypeKey);
                    }
                    if (orderClassificationList.contains(CnvTrainOrderDO.TRAIN)) {
                        assembleParam4List(listTrain, fromTypeKey);
                    }
                    if (orderClassificationList.contains(CnvCarOrderDO.CAR)) {
                        assembleParam4List(listCar, fromTypeKey);
                    }
                }
            }
        }
        canBeSeen.put(CnvFlightOrderDO.FLIGHT, listFlight);
        canBeSeen.put(CnvHotelOrderDO.HOTEL, listHotel);
        canBeSeen.put(CnvTrainOrderDO.TRAIN, listTrain);
        canBeSeen.put(CnvCarOrderDO.CAR, listCar);
        return canBeSeen;
    }

    private void assembleParam4List(List<Map<String, String>> listFlight, String fromTypeKey) {
        Map<String, String> keyMap = new ConcurrentHashMap<>();
        String[] split = fromTypeKey.split("_");
        keyMap.put("fromType", split[0]);
        keyMap.put("payType", split[1]);
        keyMap.put("channelId", split[2]);
        listFlight.add(keyMap);
    }

    private void convertDTO2VO(List<BriOrderListVO> briOrderListVOS, List<BriOrderListDTO> briOrderListDTOS, JSONObject orderClassificationAllowExpenseByChannel) {
        boolean flag = true;
        while (flag) {
            BriOrderListDTO briOrderListDTO = briOrderListDTOS.get(0);
            BriOrderInfoVO briOrderInfoVO = JSONObject.parseObject(JSON.toJSONString(briOrderListDTO), BriOrderInfoVO.class);
            BriOrderListVO briOrderListVO = JSONObject.parseObject(JSON.toJSONString(briOrderListDTO), BriOrderListVO.class);
            List<BriOrderInfoVO> briOrderInfoVOS = new CopyOnWriteArrayList<>();
            briOrderInfoVOS.add(briOrderInfoVO);
            // 将订单号相同的结果取各自的行程信息，合并到一条数据上
            for (int j = 1; j < briOrderListDTOS.size(); j++) {
                BriOrderListDTO briOrderListDTO1 = briOrderListDTOS.get(j);
                if (!StringUtils.isEmpty(briOrderListDTO.getOrderNo()) && briOrderListDTO.getOrderNo().equals(briOrderListDTO1.getOrderNo())) {
                    BriOrderInfoVO briOrderInfoVO1 = JSONObject.parseObject(JSON.toJSONString(briOrderListDTO1), BriOrderInfoVO.class);
                    briOrderInfoVOS.add(briOrderInfoVO1);
                    briOrderListDTOS.remove(briOrderListDTO1);
                    j = j - 1;
                }
            }
            if (orderClassificationAllowExpenseByChannel != null) {
                if ("Prepay".equals(briOrderListDTO.getPayType()) || "Monthlypay".equals(briOrderListDTO.getPayType())) {
                    dealWithAllowExpense(orderClassificationAllowExpenseByChannel, briOrderListDTO, briOrderListVO, "_Prepay");
                } else if ("Selfpay".equals(briOrderListDTO.getPayType())) {
                    dealWithAllowExpense(orderClassificationAllowExpenseByChannel, briOrderListDTO, briOrderListVO, "_Selfpay");
                } else {
                    briOrderListVO.setAllowExpense("0");
                }
            }
            briOrderListDTOS.remove(briOrderListDTO);
            briOrderListVO.setTravelInfo(briOrderInfoVOS);
            boolean hasNotTravelled = false;
            if (!CollectionUtils.isEmpty(briOrderInfoVOS)) {
                for (BriOrderInfoVO travelInfo : briOrderInfoVOS) {
                    if (StringUtils.isEmpty(travelInfo.getArriveDate()) || new Date().before(DateUtils.str2Date(travelInfo.getArriveDate(), "yyyy-MM-dd"))) {
                        // 未出行
                        hasNotTravelled = true;
                    }
                }
            }
            if (hasNotTravelled) {
                briOrderListVO.setHasTravelled("0");
                briOrderListVO.setAllowExpense("0");
            } else {
                briOrderListVO.setHasTravelled("1");
            }
            //添加发票信息
            Wrapper<InvoiceRelationship> wrapper = new EntityWrapper<>();
            wrapper.eq("order_no", briOrderListVO.getOrderNo());
            List<InvoiceRelationship> shipList = relationshipService.selectList(wrapper);
            List<InvoiceDTO> invoiceList = new ArrayList<>();
            for (InvoiceRelationship invoiceRelationship : shipList) {
                InvoiceDTO invoiceDTO = new InvoiceDTO();
                invoiceDTO.setBillType(invoiceRelationship.getInvoiceType());
                invoiceDTO.setInvoiceCode(invoiceRelationship.getInvoiceCode());
                invoiceDTO.setInvoiceNum(invoiceRelationship.getInvoiceNum());
                invoiceList.add(invoiceDTO);
            }
            briOrderListVO.setInvoiceList(invoiceList);

            briOrderListVOS.add(briOrderListVO);
            if (briOrderListDTOS.size() == 0) {
                flag = false;
            }
        }
    }

    private void dealWithAllowExpense(JSONObject orderClassificationAllowExpenseByChannel, BriOrderListDTO briOrderListDTO, BriOrderListVO briOrderListVO, String payType) {
        String allowExpenseStr = orderClassificationAllowExpenseByChannel.getString(briOrderListDTO.getFromType().concat(payType));
        if (!StringUtils.isEmpty(allowExpenseStr)) {
            JSONArray allowExpenseArray = JSONArray.parseArray(allowExpenseStr);
            if (allowExpenseArray.contains(briOrderListDTO.getType())) {
                briOrderListVO.setAllowExpense("1");
            } else {
                briOrderListVO.setAllowExpense("0");
            }
        }
    }

    /**
     * 获取个人订单详情
     * @param params
     * @return
     */
    @Override
    public JSONObject getBriOrderDetail(JSONObject params) {
        JSONObject result = new JSONObject();
        String type = params.getString("type");
        switch (type) {
            case "flight":
                result = briFlightOrderService.getFlightOrderJson(params);
                break;
            case "train":
                result = briTrainOrderService.getTrainOrderJson(params);
                break;
            case "hotel":
                result = briHotelOrderService.getHotelOrderJson(params);
                break;
            case "car":
                result = briCarOrderService.getCarOrderJson(params);
                break;
        }
        return result;
    }

    @Override
    public JSONObject getBriOrderDetail(String tenant, String orderNo, String type) {
        Object result = null;
        switch (type) {
            case "flight":
                result = briFlightOrderService.getFlightOrderJson(tenant, orderNo);
                break;
            case "train":
                result = briTrainOrderService.getTrainOrderJson(tenant, orderNo);
                break;
            case "hotel":
                result = briHotelOrderService.getHotelOrderJson(tenant, orderNo);
                break;
            case "car":
                result = briCarOrderService.getCarOrderJson(tenant, orderNo);
                break;
        }
        if (result != null) {
            String json = JSONObject.toJSONString(result);
            return JSONObject.parseObject(json);
        }
        return null;
    }

    @Override
    public JSONObject getOrders(String userId, String bxState, String beginDate, String endDate, String type, String tenantId) {
        JSONObject result = new JSONObject();
        JSONObject orderClassificationAllowExpenseByChannel = new JSONObject();
        List<BriChannel> enableChannelByTenant = briChannelService.getEnableChannelByTenant(tenantId);
        if (!CollectionUtils.isEmpty(enableChannelByTenant)) {
            for (BriChannel briChannel : enableChannelByTenant) {
                orderClassificationAllowExpenseByChannel.put(briChannel.getChannel().concat("_Prepay_").concat(String.valueOf(briChannel.getId())), briChannel.getReimbursementPayByEnterprise());
                orderClassificationAllowExpenseByChannel.put(briChannel.getChannel().concat("_Selfpay_").concat(String.valueOf(briChannel.getId())), briChannel.getReimbursementPayBySelf());
            }
        }
        Map<String, List<Map<String, String>>> canBeSeen = assembleCanBeSeen(orderClassificationAllowExpenseByChannel);
        JSONArray flightOrders = briFlightOrderService.getFlightOrders(userId, bxState, beginDate, endDate, tenantId, canBeSeen);
        result.put("flightOrders", flightOrders);
        JSONArray trainOrders = briTrainOrderService.getTrainOrders(userId, bxState, beginDate, endDate, tenantId, canBeSeen);
        result.put("trainOrders", trainOrders);
        JSONArray carOrders = briCarOrderService.getCarOrders(userId, bxState, beginDate, endDate, tenantId, canBeSeen);
        result.put("carOrders", carOrders);
        JSONArray hotelOrders = briHotelOrderService.getHotelOrders(userId, bxState, beginDate, endDate, tenantId, canBeSeen);
        result.put("hotelOrders", hotelOrders);
        return result;
    }

    @Override
    public JSONArray getOrders(String tenant, String type, String orderNo) {
        Object result = null;
        switch (type) {
            case "flight":
                result = briFlightOrderService.getFlightOrders(tenant, orderNo);
                break;
            case "train":
                result = briTrainOrderService.getTrainOrders(tenant, orderNo);
                break;
            case "hotel":
                result = briHotelOrderService.getHotelOrders(tenant, orderNo);
                break;
            case "car":
                result = briCarOrderService.getCarOrders(tenant, orderNo);
                break;
        }
        if (result != null) {
            return JSONArray.parseArray(JSONArray.toJSONString(result));
        }
        return null;
    }

    /**
     * 获取个人订单中心条件列表
     * @param params
     * @return
     */
    @Override
    public Map getPersonalMenuOptions(Map params) {
        String tenantId = (String) params.get("tenantId");
        Map result = new HashMap<>();
        result.put("fromType", getFromTypeOptionsByTenant(tenantId));
        result.put("orderStatus", getPersonalOrderStatusOptions());
        result.put("isInvoice", getPersonalIsInvoice());
        return result;
    }

    /**
     * 根据申请单号查询订单数据
     * @param tenantId
     * @param params
     * @return
     */
    @Override
    public JSONObject getOrdersByApplyIds(String tenantId, JSONObject params) {
        JSONObject result = new JSONObject();
        assembleOrderData(tenantId, params, result, "applyIds");
        return result;
    }

    /**
     * 根据时间范围查询订单数据
     * @param tenantId
     * @param params
     * @return
     */
    @Override
    public JSONObject getOrdersByTimeRange(String tenantId, JSONObject params) {
        JSONObject result = new JSONObject();
        if (assembleParams(params, result)) {
            return result;
        }
        assembleOrderData(tenantId, params, result, "timeRange");
        return result;
    }

    /**
     * excel导入订单数据到订单中心
     * @param tenantId
     * @param file
     * @return
     */
    @Override
    public JSONObject importOrderList(String tenantId, String type, MultipartFile file) {
        JSONObject result = new JSONObject();
        int startRow = 1;
        int endRow = 0;
        switch (type) {
            case "flight":
                List<BriFlightOrderExcelDTO> briFlightOrderExcelDTOS = null;
                try {
                    briFlightOrderExcelDTOS = (List<BriFlightOrderExcelDTO>) new ImportExcel().importExcel(file, startRow, endRow, BriFlightOrderExcelDTO.class);
                } catch (IOException e) {
                    logger.error("解析excel读取数据出错" + e);
                    throw new BusinessException("解析excel读取数据出错");
                }
                List<BriChannel> enableChannelByTenant = briChannelService.getEnableChannelByTenant(tenantId);
                if (!CollectionUtils.isEmpty(enableChannelByTenant)) {
                    if (!CollectionUtils.isEmpty(briFlightOrderExcelDTOS)) {
                        for (BriFlightOrderExcelDTO briFlightOrderExcelDTO : briFlightOrderExcelDTOS) {
                            try {
                                String orderNo = briFlightOrderExcelDTO.getOrderNo();
                                if (!StringUtils.isEmpty(orderNo)) {
                                    JSONObject orderJson = getOrderJson(briFlightOrderExcelDTO);
                                    saveFlight(orderJson, orderNo, tenantId, briFlightOrderExcelDTO.getUserId(), ChannelEnum.RTPNR.getName(), enableChannelByTenant.get(0).getId());
                                }
                            } catch (ParseException e) {
                                logger.error("订单导入出现异常", e);
                                throw new BusinessException("订单导入出现异常");
                            }
                        }
                        //生成记事
                        try {
                            pushOrdersToNotes(tenantId);
                        } catch (Exception e) {
                            logger.error(tenantId + "生成记事出现异常：" + e);
                            sendEmail2KF(e);
                        }
                    } else {
                        logger.info("excel表中未获取到订单信息" + tenantId);
                        result.put("success", false);
                        result.put("data", "excel表中未获取到订单信息");
                        return result;
                    }
                } else {
                    logger.info("根据租户" + tenantId + "未查询到相关开通信息");
                    result.put("success", false);
                    result.put("data", "根据租户未查询到相关开通信息");
                    return result;
                }
                break;
        }
        result.put("success", true);
        result.put("data", "导入成功");
        return result;
    }

    private void sendEmail2KF(Exception e) {
        Wrapper<Developer> developerWrapper = new EntityWrapper<>();
        developerWrapper.where("type={0}", "KF");
        List<Developer> developers = developerService.selectList(developerWrapper);
        String developerEmails = "";
        for (int j = 0; j < developers.size(); j++) {
            developerEmails += developers.get(j).getEmail();
            if (j < developers.size() - 1) {
                developerEmails += ",";
            }
        }
        Email email = new Email();
        String[] emails = developerEmails.split(",");
        email.setEmail(emails);
        email.setSubject(curEnv + "生成记事失败");
        email.setContent(e.getMessage());
        try {
            logger.error(e.getMessage());
            mailService.send(email);
        } catch (Exception e1) {
            logger.error("提示" + curEnv + "生成记事失败的邮件发送失败！" + e1.getMessage());
        }
    }

    private void pushOrdersToNotes(String tenantId) {
        ThreadPoolExecutorFactory.getParallelPoolExecutor().execute(new PushOrder2Note(tenantId, projecturl, notePushOrders, briSysConfigService));
    }

    private JSONObject getOrderJson(BriFlightOrderExcelDTO briFlightOrderExcelDTO) {
        JSONObject orderJson = new JSONObject();
        JSONArray flightInfoArray = new JSONArray();
        JSONObject flightInfoJson = new JSONObject();
        JSONArray flightPassengerArray = new JSONArray();
        JSONObject flightPassengerJson = new JSONObject();
        JSONArray flightContactArray = new JSONArray();
        JSONObject flightContactrJson = new JSONObject();
        orderJson.put("orderNo", briFlightOrderExcelDTO.getOrderNo());
        orderJson.put("createBy", briFlightOrderExcelDTO.getCreateBy());
        orderJson.put("userId", briFlightOrderExcelDTO.getUserId());
        orderJson.put("paymentPrice", briFlightOrderExcelDTO.getPaymentPrice());
        orderJson.put("isDomc", "国际".equals(briFlightOrderExcelDTO.getIsDomc()) ? "I" : "D");
        orderJson.put("note", briFlightOrderExcelDTO.getOrderType());
        orderJson.put("orderType", "N");
        orderJson.put("orderStatus", "NP");
        orderJson.put("tripType", "OW");
        orderJson.put("payType", "Prepay");
        orderJson.put("category", "I".equals(orderJson.getString("isDomc")) ? "rtpnr_guoji" : "rtpnr");
        orderJson.put("orderTime", DateUtils.str2Date(dealWithDateTimeFromExcel(briFlightOrderExcelDTO.getDepartureDate(), "0"), DD_DATE_FORMAT));
        //组装航程信息
        flightInfoJson.put("boardPointName", briFlightOrderExcelDTO.getBoardPointName());
        flightInfoJson.put("offPointName", briFlightOrderExcelDTO.getOffPointName());
        flightInfoJson.put("classCode", briFlightOrderExcelDTO.getClassCode());
        flightInfoJson.put("flightNo", briFlightOrderExcelDTO.getFlightNo());
        flightInfoJson.put("departureDate", DateUtils.str2Date(dealWithDateTimeFromExcel(briFlightOrderExcelDTO.getDepartureDate(), "0"), DD_DATE_FORMAT));
        flightInfoJson.put("departureTime", DateUtils.strToTime(dealWithDateTimeFromExcel(briFlightOrderExcelDTO.getDepartureDate(), "0")));
        flightInfoJson.put("arriveDate", DateUtils.str2Date(dealWithDateTimeFromExcel(briFlightOrderExcelDTO.getArriveDate(), "1"), DD_DATE_FORMAT));
        flightInfoJson.put("arriveTime", DateUtils.strToTime(dealWithDateTimeFromExcel(briFlightOrderExcelDTO.getArriveDate(), "1")));
        flightInfoArray.add(flightInfoJson);
        orderJson.put("flightInfo", flightInfoArray);
        //组装乘客信息
        flightPassengerJson.put("psgName", briFlightOrderExcelDTO.getCreateBy());
        flightPassengerJson.put("OAUserCode", briFlightOrderExcelDTO.getUserId());
        flightPassengerArray.add(flightPassengerJson);
        orderJson.put("flightPassenger", flightPassengerArray);
        //组装联系人信息
        flightContactrJson.put("contactName", briFlightOrderExcelDTO.getCreateBy());
        flightContactArray.add(flightContactrJson);
        orderJson.put("flightContact", flightContactArray);
        return orderJson;
    }

    //处理表格中的时间：由于有些没有飞机到达和起飞时间，则默认导入日期为起飞日期，起飞时间为：0:00， 到达时间为23:59；若有则使用表格中时间
    private String dealWithDateTimeFromExcel(String dateTime, String dateType) {
        if (!StringUtils.isEmpty(dateTime)) {
            if (dateTime.contains("/")) {
                dateTime = dateTime.replace("/", "-");
            }
            if (dateTime.trim().length() == 10) {
                dateTime = dateTime.concat(" 00:00:00");
            }
            Time time = DateUtils.strToTime(dateTime);
            if ("00:00:00".equals(String.valueOf(time))) {
                if ("1".equals(dateType)) {
                    //补全到达时间
                    dateTime = dateTime.substring(0, 10) + " " + "23:59:59";
                }
            }
        }
        return dateTime;
    }

    /**
     * 组装查询到的订单数据
     * @param tenantId
     * @param params
     * @param result
     * @param queryType
     */
    private void assembleOrderData(String tenantId, JSONObject params, JSONObject result, String queryType) {
        assembleFlightOrderData(tenantId, result, params, queryType);
        assembleHotelOrderData(tenantId, result, params, queryType);
        assembleTrainOrderData(tenantId, result, params, queryType);
        assembleCarOrderData(tenantId, result, params, queryType);
    }

    /**
     * 组装查询参数
     * @param params
     * @param result
     * @return
     */
    private boolean assembleParams(JSONObject params, JSONObject result) {
        String begin = params.getString("begin");
        String end = params.getString("end");
        if (StringUtils.isEmpty(begin) || StringUtils.isEmpty(end)) {
            result.put("message", "请检查参数，begin和end不允许为空");
            return true;
        }
        Date beginDate = DateUtils.str2Date(begin, "yyyy-MM-dd HH:mm:ss");
        Date endDate = DateUtils.str2Date(end, "yyyy-MM-dd HH:mm:ss");
        String orderType = params.getString("orderType");
        if (StringUtils.isEmpty(orderType)) {
            orderType = "7";
        }
        params.put("begin", beginDate);
        params.put("end", endDate);
        params.put("orderType", orderType);
        return false;
    }



    /**
     * 查询并组装火车订单数据
     * @param tenantId
     * @param result
     * @param params
     * @param queryType
     */
    private void assembleTrainOrderData(String tenantId, JSONObject result, JSONObject params, String queryType) {
        List<BriTrainOrder> briTrainOrders = new CopyOnWriteArrayList<>();
        if ("applyIds".equals(queryType)) {
            JSONArray trains = params.getJSONArray("train");
            if (!CollectionUtils.isEmpty(trains)) {
                briTrainOrders = briTrainOrderService.getOrdersByRelateYBZId(trains.toJavaList(String.class));
            }
        } else if ("timeRange".equals(queryType)) {
            // TODO 提供数组内任意个数的和的方法（目前是将和的所有情况写在代码里，以后需要修改）
            String[] orderTypeArray = {"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "28", "29", "30", "31"};
            List<String> orderTypes =  Arrays.asList(orderTypeArray);
            Date begin = params.getDate("begin");
            Date end = params.getDate("end");
            String orderType = params.getString("orderType");
            if (orderTypes.contains(orderType)) {
                briTrainOrders = briTrainOrderService.getOrdersByTimeRange(tenantId, begin, end);
            }
        }
        //对通过不同方式查询到的订单数据进行组装
        if (!CollectionUtils.isEmpty(briTrainOrders)) {
            JSONArray trainOrders = new JSONArray();
            if (!CollectionUtils.isEmpty(briTrainOrders)) {
                for (BriTrainOrder briTrainOrder : briTrainOrders) {
                    JSONObject trainOrderJson = JSONObject.parseObject(JSON.toJSONString(briTrainOrder));
                    String orderNo = briTrainOrder.getOrderNo();
                    if (!StringUtils.isEmpty(orderNo)) {
                        JSONArray trainPassengers = new JSONArray();
                        List<BriTrainPassenger> briTrainPassengers = briTrainPassengerService.getBriTrainPassenger(orderNo);
                        List<BriTrainPayment> briTrainPayments = briTrainPassengerService.getBriTrainPayment(orderNo);
                        if (!CollectionUtils.isEmpty(briTrainPassengers)) {
                            for (BriTrainPassenger briTrainPassenger : briTrainPassengers) {
                                JSONObject trainPassengerJson = JSONObject.parseObject(JSON.toJSONString(briTrainPassenger));
                                String cardNo = briTrainPassenger.getCardNo();
                                List<BriTrainTicket> briTrainTickets = briTrainTicketService.getBriTrainTicketByOrderNoAndCardNo(orderNo, cardNo);
                                trainPassengerJson.put(BriTrainOrder.TRAINTICKETS, briTrainTickets);
                                trainPassengers.add(trainPassengerJson);
                            }
                            trainOrderJson.put(BriTrainOrder.TRAINPASSENGERS, trainPassengers);
                            trainOrderJson.put(BriTrainOrder.TRAINPAYMENTS, briTrainPayments);
                        }
                    }
                    trainOrders.add(trainOrderJson);
                }
            }
            result.put(BriTrainOrder.TRAINORDERS, trainOrders);
        }
    }

    /**
     * 查询并组装酒店订单数据
     * @param tenantId
     * @param result
     * @param params
     * @param queryType
     */
    private void assembleHotelOrderData(String tenantId, JSONObject result, JSONObject params, String queryType) {
        List<BriHotelOrder> briHotelOrders = new CopyOnWriteArrayList<>();
        if ("applyIds".equals(queryType)) {
            JSONArray hotels = params.getJSONArray("hotel");
            if (!CollectionUtils.isEmpty(hotels)) {
                briHotelOrders = briHotelOrderService.getOrdersByRelateYBZId(hotels.toJavaList(String.class));
            }
        } else if ("timeRange".equals(queryType)) {
            String[] orderTypeArray = {"4", "5", "6", "7", "12", "13", "14", "15", "20", "21", "22", "28", "29", "30", "31"};
            List<String> orderTypes =  Arrays.asList(orderTypeArray);
            Date begin = params.getDate("begin");
            Date end = params.getDate("end");
            String orderType = params.getString("orderType");
            if (orderTypes.contains(orderType)) {
                briHotelOrders = briHotelOrderService.getHotelOrdersByTimeRange(tenantId, begin, end);
            }
        }
        if (!CollectionUtils.isEmpty(briHotelOrders)) {
            JSONArray hotelOrders = new JSONArray();
            if (!CollectionUtils.isEmpty(briHotelOrders)) {
                for (BriHotelOrder briHotelOrder : briHotelOrders) {
                    JSONObject hotelOrderJson = JSONObject.parseObject(JSON.toJSONString(briHotelOrder));
                    String orderNo = briHotelOrder.getOrderNo();
                    if (!StringUtils.isEmpty(orderNo)) {
                        List<BriHotelRoom> briHotelRooms = briHotelRoomService.getBriHotelRoom(orderNo);
                        hotelOrderJson.put(BriHotelOrder.HOTELROOMS, briHotelRooms);
                    }
                    hotelOrders.add(hotelOrderJson);
                }
            }
            result.put(BriHotelOrder.HOTELORDERS, hotelOrders);
        }
    }

    /**
     * 查询并组装用车订单数据
     * @param tenantId
     * @param result
     * @param params
     * @param queryType
     */
    private void assembleCarOrderData(String tenantId, JSONObject result, JSONObject params, String queryType) {
        List<BriCarOrder> briCarOrders = new CopyOnWriteArrayList<>();
        if ("applyIds".equals(queryType)) {
            JSONArray cars = params.getJSONArray("car");
            if (!CollectionUtils.isEmpty(cars)) {
                briCarOrders = briCarOrderService.getOrdersByRelateYBZId(cars.toJavaList(String.class));
            }
        } else if ("timeRange".equals(queryType)) {
            String[] orderTypeArray = {"8", "9", "10", "11", "12", "13", "14", "15", "24", "25", "26", "27", "28", "30", "31"};
            List<String> orderTypes =  Arrays.asList(orderTypeArray);
            Date begin = params.getDate("begin");
            Date end = params.getDate("end");
            String orderType = params.getString("orderType");
            if (orderTypes.contains(orderType)) {
                briCarOrders = briCarOrderService.getCarOrdersByTimeRange(tenantId, begin, end);
            }
        }
        if (!CollectionUtils.isEmpty(briCarOrders)) {
            JSONArray carOrders = new JSONArray();
            if (!CollectionUtils.isEmpty(briCarOrders)) {
                for (BriCarOrder briCarOrder : briCarOrders) {
                    carOrders.add(briCarOrder);
                }
            }
            result.put(BriCarOrder.CARORDERS, carOrders);
        }
    }

    /**
     * 查询并组装机票订单数据
     * @param tenantId
     * @param result
     * @param params
     * @param queryType
     */
    private void assembleFlightOrderData(String tenantId, JSONObject result, JSONObject params, String queryType) {
        List<BriFlightOrder> briFlightOrders = new CopyOnWriteArrayList<>();
        if ("applyIds".equals(queryType)) {
            JSONArray flights = params.getJSONArray("flight");
            if (!CollectionUtils.isEmpty(flights)) {
                briFlightOrders = briFlightOrderService.getOrdersByRelateYBZId(flights.toJavaList(String.class));
            }
        } else if ("timeRange".equals(queryType)) {
            String[] orderTypeArrayD = {"1", "3", "5", "7", "9", "11", "13", "15", "17", "19", "21", "23", "25", "29", "31"};
            String[] orderTypeArrayN = {"2", "3", "6", "7", "10", "11", "14", "15", "18", "19", "22", "23", "26", "30", "31"};
            List<String> orderTypesD =  Arrays.asList(orderTypeArrayD);
            List<String> orderTypesN =  Arrays.asList(orderTypeArrayN);
            Date begin = params.getDate("begin");
            Date end = params.getDate("end");
            String orderType = params.getString("orderType");
            if (orderTypesD.contains(orderType) && orderTypesN.contains(orderType)) {
                briFlightOrders = briFlightOrderService.getFlightOrdersByTimeRange(tenantId, begin, end, "");
            } else if (orderTypesD.contains(orderType)) {
                briFlightOrders = briFlightOrderService.getFlightOrdersByTimeRange(tenantId, begin, end, "D");
            } else if (orderTypesN.contains(orderType)) {
                briFlightOrders = briFlightOrderService.getFlightOrdersByTimeRange(tenantId, begin, end, "N");
            }
        }
        if (!CollectionUtils.isEmpty(briFlightOrders)) {
            JSONArray flightOrders = new JSONArray();
            if (!CollectionUtils.isEmpty(briFlightOrders)) {
                for (BriFlightOrder briFlightOrder : briFlightOrders) {
                    JSONObject flightOrderJson = JSONObject.parseObject(JSON.toJSONString(briFlightOrder));
                    String orderNo = briFlightOrder.getOrderNo();
                    if (!StringUtils.isEmpty(orderNo)) {
                        List<BriFlightInfo> briFlightInfos = briFlightInfoService.getBriFlightInfo(orderNo);
                        List<BriFlightPassenger> briFlightPassengers = briFlightPassengerService.getBriFlightPassenger(orderNo);
                        List<BriFlightOrderContact> briFlightOrderContacts = briFlightOrderContactService.getBriFlightOrderContact(orderNo);
                        flightOrderJson.put(BriFlightOrder.FLIGHTINFOS, briFlightInfos);
                        flightOrderJson.put(BriFlightOrder.FLIGHTPASSENGERS, briFlightPassengers);
                        flightOrderJson.put(BriFlightOrder.FLIGHTORDERCONTACTS, briFlightOrderContacts);
                    }
                    flightOrders.add(flightOrderJson);
                }
            }
            result.put(BriFlightOrder.FLIGHTORDERS, flightOrders);
        }
    }

    private JSONArray getPersonalIsInvoice() {
        JSONArray isInvoices = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("label", "未开票");
        jsonObject1.put("value", "0");
        isInvoices.add(jsonObject1);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("label", "已开票");
        jsonObject2.put("value", "1");
        isInvoices.add(jsonObject2);
        return isInvoices;
    }

    private JSONArray getPersonalOrderStatusOptions() {
        JSONArray orderStatuses = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("label", "已使用");
        jsonObject1.put("value", "NP");
        orderStatuses.add(jsonObject1);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("label", "未使用");
        jsonObject2.put("value", "NW");
        orderStatuses.add(jsonObject2);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("label", "已取消");
        jsonObject3.put("value", "CO");
        orderStatuses.add(jsonObject3);
        JSONObject jsonObject4 = new JSONObject();
        jsonObject4.put("label", "已退票");
        jsonObject4.put("value", "TP");
        orderStatuses.add(jsonObject4);
        JSONObject jsonObject5 = new JSONObject();
        jsonObject5.put("label", "已改签");
        jsonObject5.put("value", "GT");
        orderStatuses.add(jsonObject5);
        return orderStatuses;
    }

    private JSONArray getFromTypeOptionsByTenant(String tenantId) {
        JSONArray fromTypes = new JSONArray();
        List<BriChannel> briChannels = briChannelService.getEnableChannelByTenant(tenantId);
        if (!CollectionUtils.isEmpty(briChannels)) {
            for (BriChannel briChannel : briChannels) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label", getFromTypeName(briChannel.getChannel()));
                jsonObject.put("value", briChannel.getChannel());
                fromTypes.add(jsonObject);
            }
        }
        return fromTypes;
    }

    private String getFromTypeName(String channel) {
        switch (channel) {
            case "rtpnr" :
                return "中航易购";
            case "ctripBC" :
                return "携程";
            case "ctripSME" :
                return "携程商旅通";
            case "tujia" :
                return "途家";
            case "clyh" :
                return "差旅壹号";
            case "tuniu" :
                return "途牛";
            case "ystrip" :
                return "云上火车票";
            case "zteitc" :
                return "中兴";
            case "fanscar" :
                return "泛嘉";
            case "didi" :
                return "滴滴";
            case "meiya" :
                return "美亚";
            case "HCHoliday" :
                return "花城";
            default :
                return "";
        }
    }

    /**
     * 根据申请单号补全订单中的申请单相关数据
     * @param relateYBZIds
     * @param tenantId
     */
    @Override
    public void updateSQByRelateYbzIds(JSONArray relateYBZIds, String tenantId) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = relateYBZIds.toJavaList(String.class);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("tenant", tenantId);
        paramMap.put("pagenum", 10);
        paramMap.put("pks", applyIdList);
        //暂时没传电话
        String phone = "";
        while (flag) {
            paramMap.put("page", page++);
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenantId + "paramMap=" + JSON.toJSONString(paramMap));
            String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenantId, headers, null, JSON.toJSONString(paramMap));
            logger.info("nodeBusinessTripSearching's result according applyId:" + res);
            JSONObject resObject = JSON.parseObject(res);
            if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                JSONArray data = resObject.getJSONArray("data");
                if (!CollectionUtils.isEmpty(data)) {
                    for (Object datum : data) {
                        JSONObject datumJson = JSONObject.parseObject(String.valueOf(datum));
                        if (datumJson.getBoolean("success")) {
                            for (Object relateYBZIdObject : relateYBZIds) {
                                String relateYBZId = String.valueOf(relateYBZIdObject);
                                if (!CollectionUtils.isEmpty(datumJson.getJSONArray("pk")) && datumJson.getJSONArray("pk").contains(relateYBZId)) {
                                    //flight
                                    EntityWrapper<BriFlightOrder> flightOrderEntityWrapper = new EntityWrapper<>();
                                    flightOrderEntityWrapper.where("tenant={0}", tenantId);
                                    flightOrderEntityWrapper.and("relate_ybz_id={0}", relateYBZId);
                                    List<BriFlightOrder> briFlightOrders = briFlightOrderService.selectList(flightOrderEntityWrapper);
                                    if (!CollectionUtils.isEmpty(briFlightOrders)) {
                                        for (BriFlightOrder briFlightOrder : briFlightOrders) {
                                            JSONArray heads = datumJson.getJSONArray("head");
                                            dealFlightWithSQ(briFlightOrder, heads, !CollectionUtils.isEmpty(heads));
                                        }
                                        briFlightOrderService.updateBatchById(briFlightOrders);
                                    }
                                    //train
                                    EntityWrapper<BriTrainOrder> trainOrderEntityWrapper = new EntityWrapper<>();
                                    trainOrderEntityWrapper.where("tenant={0}", tenantId);
                                    trainOrderEntityWrapper.and("relate_ybz_id={0}", relateYBZId);
                                    List<BriTrainOrder> briTrainOrders = briTrainOrderService.selectList(trainOrderEntityWrapper);
                                    if (!CollectionUtils.isEmpty(briTrainOrders)) {
                                        for (BriTrainOrder briTrainOrder : briTrainOrders) {
                                            JSONArray heads = datumJson.getJSONArray("head");
                                            dealTrainWithSQ(briTrainOrder, heads, !CollectionUtils.isEmpty(heads));
                                        }
                                        briTrainOrderService.updateBatchById(briTrainOrders);
                                    }
                                    //hotel
                                    EntityWrapper<BriHotelOrder> hotelOrderEntityWrapper = new EntityWrapper<>();
                                    hotelOrderEntityWrapper.where("tenant={0}", tenantId);
                                    hotelOrderEntityWrapper.and("relate_ybz_id={0}", relateYBZId);
                                    List<BriHotelOrder> briHotelOrders = briHotelOrderService.selectList(hotelOrderEntityWrapper);
                                    if (!CollectionUtils.isEmpty(briHotelOrders)) {
                                        for (BriHotelOrder briHotelOrder : briHotelOrders) {
                                            JSONArray heads = datumJson.getJSONArray("head");
                                            dealHotelWithSQ(briHotelOrder, heads, !CollectionUtils.isEmpty(heads));
                                        }
                                        briHotelOrderService.updateBatchById(briHotelOrders);
                                    }
                                    //car
                                    EntityWrapper<BriCarOrder> carOrderEntityWrapper = new EntityWrapper<>();
                                    carOrderEntityWrapper.where("tenant={0}", tenantId);
                                    carOrderEntityWrapper.and("in_approve_id={0}", relateYBZId);
                                    List<BriCarOrder> briCarOrders = briCarOrderService.selectList(carOrderEntityWrapper);
                                    if (!CollectionUtils.isEmpty(briCarOrders)) {
                                        for (BriCarOrder briCarOrder : briCarOrders) {
                                            JSONArray heads = datumJson.getJSONArray("head");
                                            dealCarWithSQ(briCarOrder, heads, !CollectionUtils.isEmpty(heads));
                                        }
                                        briCarOrderService.updateBatchById(briCarOrders);
                                    }
                                }
                            }
                        }
                    }
                }
                //最后一页跳出循环
                if (resObject.getInteger("totalPage") < page) {
                    flag = false;
                }
            } else {
                flag = false;
                logger.error("根据关联申请单号匹配申请单时，返回错误");
            }

        }
    }

    private void dealTrainWithSQ(BriTrainOrder briTrainOrder, JSONArray heads, boolean b) {
        if (b) {
            for (Object head : heads) {
                JSONObject headJsonObject = (JSONObject) head;
                if (BriTrainOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        briTrainOrder.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briTrainOrder.setAssumeOrg(headJsonObject.getString("source_value"));
                    }
                }
                if (BriTrainOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        briTrainOrder.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briTrainOrder.setAssumeDept(headJsonObject.getString("source_value"));
                    }
                }
                if (BriTrainOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        briTrainOrder.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briTrainOrder.setCostProject(headJsonObject.getString("source_value"));
                    }
                }
                if (BriTrainOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        briTrainOrder.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briTrainOrder.setApplyUser(headJsonObject.getString("source_value"));
                    }
                }
                if (BriTrainOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof String) {
                        briTrainOrder.setCompanion(headJsonObject.getString("source_value"));
                    }
                }
            }
        }
    }

    private void dealFlightWithSQ(BriFlightOrder briFlightOrder, JSONArray heads, Boolean b) {
        if (b) {
            for (Object head : heads) {
                JSONObject headJsonObject = (JSONObject) head;
                if (BriFlightOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        briFlightOrder.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briFlightOrder.setAssumeOrg(headJsonObject.getString("source_value"));
                    }
                }
                if (BriFlightOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        briFlightOrder.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briFlightOrder.setAssumeDept(headJsonObject.getString("source_value"));
                    }
                }
                if (BriFlightOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        briFlightOrder.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briFlightOrder.setCostProject(headJsonObject.getString("source_value"));
                    }
                }
                if (BriFlightOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        briFlightOrder.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        briFlightOrder.setApplyUser(headJsonObject.getString("source_value"));
                    }
                }
                if (BriFlightOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof String) {
                        briFlightOrder.setCompanion(headJsonObject.getString("source_value"));
                    }
                }
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveTrain(JSONObject orderJson, String orderNo, String tenant, String orderUserOutStaffNo, String fromType, int channelId) {
        // 如果此订单已关联报销单，则不会重新拉取
        ExpenseStatus expenseStatus = expenseStatusService.hasOrderReimbursed(orderNo);
        if (expenseStatus != null) {
            return;
        }
        orderJson.put("channelId", channelId);
        orderJson.put("fromType", fromType);
        BriTrainOrder trainOrderByJSON = OrderCenterConvert.getTrainOrderByJSON(orderJson);
        trainOrderByJSON.setOrderNo(orderNo);
        trainOrderByJSON.setTenant(tenant);
        // 补全用户信息
        if (!StringUtils.isEmpty(orderUserOutStaffNo)) {
            try {
                UcUserDto ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(orderUserOutStaffNo, tenant);
                if (null != ucUser) {
                    trainOrderByJSON.setOrgPk(ucUser.getOrgPk());
                    trainOrderByJSON.setDeptPk(ucUser.getDeptPk());
                    trainOrderByJSON.setDepartment(ucUser.getDeptName());
                    trainOrderByJSON.setUserId(ucUser.getUserId());
                    if (ChannelEnum.FANSCAR.getName().equals(fromType)) {
                        trainOrderByJSON.setCreateBy(ucUser.getUserName());
                    }
                }
            } catch (Exception e) {
                logger.error("用户中心查询用户信息出错getOrderList.saveTrain" + e.getMessage());
            }
        }

        //根据申请单id补全申请单信息
        dealWithApplyTrain(tenant, trainOrderByJSON);

        if (trainOrderByJSON != null) {
            Wrapper<BriTrainOrder> briTrainOrderWrapper = new EntityWrapper<>();
            briTrainOrderWrapper.where("order_no={0}", orderNo);
            List<BriTrainOrder> briTrainOrders = briTrainOrderService.selectList(briTrainOrderWrapper);
            if (briTrainOrders != null && briTrainOrders.size() > 0) {
                if ("1".equals(briTrainOrders.get(0).getIsNote())) {
                    return;
                }
                briTrainOrderService.delete(briTrainOrderWrapper);
                briTrainOrderService.insert(trainOrderByJSON);
            } else {
                briTrainOrderService.insert(trainOrderByJSON);
            }
            //存储乘客信息
            JSONArray passengers = orderJson.getJSONArray("passengers");
            if (passengers != null && passengers.size() > 0) {
                List<BriTrainPassenger> briTrainPassengers = new CopyOnWriteArrayList<>();
                for (int i = 0; i < passengers.size(); i++) {
                    JSONObject passenger = passengers.getJSONObject(i);
                    BriTrainPassenger trainPassenger = null;
                    trainPassenger = OrderCenterConvert.getBriTrainPassengerByJSON(passenger, orderNo);
                    briTrainPassengers.add(trainPassenger);

                    //存储票信息
                    JSONArray tickets = passenger.getJSONArray("tickets");
                    String cardNo = trainPassenger.getCardNo();
                    List<BriTrainTicket> trainTickets = null;
                    trainTickets = OrderCenterConvert.getBriTrainTicketByJSON(tickets, orderNo, cardNo);
                    Wrapper<BriTrainTicket> briTrainTicketWrapper = new EntityWrapper<>();
                    briTrainTicketWrapper.where("order_no={0}", orderNo);
                    if (!StringUtils.isEmpty(cardNo)) {
                        briTrainTicketWrapper.and("card_no={0}", cardNo);
                    }
                    briTrainTicketService.delete(briTrainTicketWrapper);
                    if (trainTickets != null && trainTickets.size() > 0) {
                        briTrainTicketService.insertBatch(trainTickets);
                    }
                    //end 存储票信息
                }
                Wrapper<BriTrainPassenger> briTrainPassengerWrapper = new EntityWrapper<>();
                briTrainPassengerWrapper.where("order_no={0}", orderNo);
                briTrainPassengerService.delete(briTrainPassengerWrapper);
                if (!CollectionUtils.isEmpty(briTrainPassengers)) {
                    briTrainPassengerService.insertBatch(briTrainPassengers);
                }
                //end 存储乘客信息
            }

            //存储支付信息
            List<BriTrainPayment> trainPayments = null;
            trainPayments = OrderCenterConvert.getBriTrainPaymentByJSON(orderJson, orderNo);
            Wrapper<BriTrainPayment> briTrainPaymentWrapper = new EntityWrapper<>();
            briTrainPaymentWrapper.where("order_no={0}", orderNo);
            briTrainPaymentService.delete(briTrainPaymentWrapper);
            if (trainPayments != null && trainPayments.size() > 0) {
                briTrainPaymentService.insertBatch(trainPayments);
            }
            //end 存储支付信息
        }
    }

    private void dealWithApplyTrain(String tenant, BriTrainOrder trainOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(trainOrderByJSON.getRelateYBZID())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(trainOrderByJSON.getRelateYBZID());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            dealTrainWithSQ(trainOrderByJSON, heads, !CollectionUtils.isEmpty(heads));
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    @Transactional
    @Override
    public void saveCar(JSONObject orderJson, String orderId, String tenant, String personCodeOrPhone, String fromType, int channelId) {
        // 如果此订单已关联报销单，则不会重新拉取
        ExpenseStatus expenseStatus = expenseStatusService.hasOrderReimbursed(orderId);
        if (expenseStatus != null) {
            return;
        }
        orderJson.put("channelId", channelId);
        orderJson.put("fromType", fromType);
        BriCarOrder carOrderByJSON = OrderCenterConvert.getBriCarOrderFromJSON(orderJson);
        carOrderByJSON.setOrderNo(orderId);
        carOrderByJSON.setTenant(tenant);
        // 补全用户信息
        if (!StringUtils.isEmpty(personCodeOrPhone)) {
            try {
                UcUserDto ucUser = null;
                if (ChannelEnum.TUJIA.getName().equals(carOrderByJSON.getFromType()) || ChannelEnum.DIDI.getName().equals(carOrderByJSON.getFromType()) || ChannelEnum.RTPNR.getName().equals(carOrderByJSON.getFromType())) {
                    ucUser = userCenterService.getCompleteUcUserDtoByPhone(personCodeOrPhone, tenant);
                } else {
                    ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(personCodeOrPhone, tenant);
                }
                if (null != ucUser) {
                    carOrderByJSON.setOrgPk(ucUser.getOrgPk());
                    carOrderByJSON.setDeptPk(ucUser.getDeptPk());
                    carOrderByJSON.setDepartment(ucUser.getDeptName());
                    carOrderByJSON.setUserId(ucUser.getUserId());
                    if (ChannelEnum.FANSCAR.getName().equals(fromType)) {
                        carOrderByJSON.setCreateBy(ucUser.getUserName());
                    }
                }
            } catch (Exception e) {
                logger.error("用户中心查询用户信息出错getOrderList.saveFlight" + e.getMessage());
            }

            //根据申请单id补全申请单信息
            dealWithApplyCar(tenant, carOrderByJSON);

            if (carOrderByJSON != null) {
                Wrapper<BriCarOrder> briCarOrderWrapper = new EntityWrapper<>();
                briCarOrderWrapper.where("order_no={0}", orderId);
                List<BriCarOrder> briCarOrders = briCarOrderService.selectList(briCarOrderWrapper);
                if (briCarOrders != null && briCarOrders.size() > 0) {
                    if ("1".equals(briCarOrders.get(0).getIsNote())) {
                        return;
                    }
                    //滴滴：用友股份和用友分子公司的配置信息完全相同，需根据用户中心来判断人员所属租户，订单保存到相应租户下
                    if (("uq0dskd6".equals(tenant) || "ft9fbcrw".equals(tenant)) && StringUtils.isEmpty(carOrderByJSON.getUserId())) {
                        carOrderByJSON.setTenant("");
                    }
                    briCarOrderService.delete(briCarOrderWrapper);
                    briCarOrderService.insert(carOrderByJSON);
                } else {
                    briCarOrderService.insert(carOrderByJSON);
                }
            }
        }
    }

    private void dealWithApplyCar(String tenant, BriCarOrder carOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(carOrderByJSON.getInApproveId())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(carOrderByJSON.getInApproveId());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            dealCarWithSQ(carOrderByJSON, heads, !CollectionUtils.isEmpty(heads));
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    private void dealCarWithSQ(BriCarOrder carOrderByJSON, JSONArray heads, boolean b) {
        if (b) {
            for (Object head : heads) {
                JSONObject headJsonObject = (JSONObject) head;
                if (BriCarOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        carOrderByJSON.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        carOrderByJSON.setAssumeOrg(headJsonObject.getString("source_value"));
                    }
                }
                if (BriCarOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        carOrderByJSON.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        carOrderByJSON.setAssumeDept(headJsonObject.getString("source_value"));
                    }
                }
                if (BriCarOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        carOrderByJSON.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        carOrderByJSON.setCostProject(headJsonObject.getString("source_value"));
                    }
                }
                if (BriCarOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject){
                        carOrderByJSON.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        carOrderByJSON.setApplyUser(headJsonObject.getString("source_value"));
                    }
                }
                if (BriCarOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof String) {
                        carOrderByJSON.setCompanion(headJsonObject.getString("source_value"));
                    }
                }
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFlight(JSONObject orderJson, String orderNo, String tenant, String personCodeOrPhone, String fromType, int channelId) throws ParseException {
        // 如果此订单已关联报销单，则不会重新拉取
        ExpenseStatus expenseStatus = expenseStatusService.hasOrderReimbursed(orderNo);
        if (expenseStatus != null) {
            return;
        }
        orderJson.put("channelId", channelId);
        orderJson.put("fromType", fromType);
        BriFlightOrder flightOrderByJSON = OrderCenterConvert.getFlightOrderByJSON(orderJson);
        flightOrderByJSON.setOrderNo(orderNo);
        flightOrderByJSON.setTenant(tenant);
        if (!StringUtils.isEmpty(orderJson.getString("updateTime"))) {
//            flightOrderByJSON.setSysUpdateTime(DateUtils.strToDateTime(orderJson.getString("updateTime")));
            flightOrderByJSON.setSysUpdateTime(DateUtils.str2Date(orderJson.getString("updateTime"),DateUtils.DD_DATETIME_FORMAT));
        }
        // 补全用户信息
        if (!StringUtils.isEmpty(personCodeOrPhone)) {
            try {
                UcUserDto ucUser = null;
                if (ChannelEnum.TUJIA.getName().equals(flightOrderByJSON.getFromType()) || ChannelEnum.ZHJW.getName().equals(flightOrderByJSON.getFromType())) {
                    ucUser = userCenterService.getCompleteUcUserDtoByPhone(personCodeOrPhone, tenant);
                } else {
                    ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(personCodeOrPhone, tenant);
                }
                if (null != ucUser) {
                    flightOrderByJSON.setOrgPk(ucUser.getOrgPk());
                    flightOrderByJSON.setDeptPk(ucUser.getDeptPk());
                    flightOrderByJSON.setDepartment(ucUser.getDeptName());
                    flightOrderByJSON.setUserId(ucUser.getUserId());
                    if (ChannelEnum.FANSCAR.getName().equals(fromType)) {
                        flightOrderByJSON.setCreateBy(ucUser.getUserName());
                    }
                }
            } catch (Exception e) {
                logger.error("用户中心查询用户信息出错getOrderList.saveFlight" + e.getMessage());
            }
        }
        //根据申请单id补全申请单信息
        dealWithApplyFlight(tenant, flightOrderByJSON);

        if (flightOrderByJSON != null) {
            Wrapper<BriFlightOrder> briFlightOrderWrapper = new EntityWrapper<>();
            briFlightOrderWrapper.where("order_no={0}", orderNo);
            List<BriFlightOrder> briFlightOrders = briFlightOrderService.selectList(briFlightOrderWrapper);
            if (briFlightOrders != null && briFlightOrders.size() > 0) {
                if ("1".equals(briFlightOrders.get(0).getIsNote())) {
                    return;
                }
                briFlightOrderService.delete(briFlightOrderWrapper);
                briFlightOrderService.insert(flightOrderByJSON);
            } else {
                briFlightOrderService.insert(flightOrderByJSON);
            }

            //存储航班信息
            List<BriFlightInfo> flightInfos = null;
            flightInfos = OrderCenterConvert.getBriFlightInfoByJSON(orderJson, orderNo);
            Wrapper<BriFlightInfo> briFlightInfoWrapper = new EntityWrapper<>();
            briFlightInfoWrapper.where("order_no={0}", orderNo);
            briFlightInfoService.delete(briFlightInfoWrapper);
            if (flightInfos != null && flightInfos.size() > 0) {
                briFlightInfoService.insertBatch(flightInfos);
            }
            //end 存储航班信息

            //存储出行人信息
            List<BriFlightPassenger> flightPassengers = null;
            flightPassengers = OrderCenterConvert.getBriFlightPassengerByJSON(orderJson, orderNo);
            Wrapper<BriFlightPassenger> briFlightPassengerWrapper = new EntityWrapper<>();
            briFlightPassengerWrapper.where("order_no={0}", orderNo);
            briFlightPassengerService.delete(briFlightPassengerWrapper);
            if (flightPassengers != null && flightPassengers.size() > 0) {
                briFlightPassengerService.insertBatch(flightPassengers);
            }
            //end 存储出行人信息

            //存储联系人信息
            List<BriFlightOrderContact> flightOrderContacts = null;
            flightOrderContacts = OrderCenterConvert.getBriFlightOrderContactByJSON(orderJson, orderNo);
            Wrapper<BriFlightOrderContact> briFlightOrderContactWrapper = new EntityWrapper<>();
            briFlightOrderContactWrapper.where("order_no={0}", orderNo);
            briFlightOrderContactService.delete(briFlightOrderContactWrapper);
            if (flightOrderContacts != null && flightOrderContacts.size() > 0) {
                briFlightOrderContactService.insertBatch(flightOrderContacts);
            }
            //end 存储联系人信息
        }
    }

    /**
     * 通过调用ybz服务为申请单相关字段赋值
     *
     * @param tenant
     * @param flightOrderByJSON
     */
    private void dealWithApplyFlight(String tenant, BriFlightOrder flightOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(flightOrderByJSON.getRelateYbzId())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(flightOrderByJSON.getRelateYbzId());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            dealFlightWithSQ(flightOrderByJSON, heads, !CollectionUtils.isEmpty(heads));
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveHotel(JSONObject orderJson, String orderNo, String tenant, String personCodeOrPhone, String fromType, int channelId) throws ParseException {
        // 如果此订单已关联报销单，则不会重新拉取
        ExpenseStatus expenseStatus = expenseStatusService.hasOrderReimbursed(orderNo);
        if (expenseStatus != null) {
            return;
        }
        orderJson.put("channelId", channelId);
        orderJson.put("fromType", fromType);
        BriHotelOrder hotelOrderByJSON = OrderCenterConvert.getHotelOrderByJSON(orderJson);
        hotelOrderByJSON.setOrderNo(orderNo);
        hotelOrderByJSON.setTenant(tenant);
        // 补全用户信息
        if (!StringUtils.isEmpty(personCodeOrPhone)) {
            try {
                UcUserDto ucUser = null;
                if (ChannelEnum.TUJIA.getName().equals(hotelOrderByJSON.getFromType())) {
                    ucUser = userCenterService.getCompleteUcUserDtoByPhone(personCodeOrPhone, tenant);
                } else {
                    ucUser = userCenterService.getCompleteUcUserDtoByPersonCode(personCodeOrPhone, tenant);
                }
                if (null != ucUser) {
                    hotelOrderByJSON.setOrgPk(ucUser.getOrgPk());
                    hotelOrderByJSON.setDeptPk(ucUser.getDeptPk());
                    hotelOrderByJSON.setDepartment(ucUser.getDeptName());
                    hotelOrderByJSON.setUserId(ucUser.getUserId());
                    if (ChannelEnum.FANSCAR.getName().equals(fromType)) {
                        hotelOrderByJSON.setCreateBy(ucUser.getUserName());
                    }
                }
            } catch (Exception e) {
                logger.error("用户中心查询用户信息出错getOrderList.saveHotel" + e.getMessage());
            }
        }

        //根据申请单id补全申请单信息
        dealWithApplyHotel(tenant, hotelOrderByJSON);

        if (hotelOrderByJSON != null) {
            Wrapper<BriHotelOrder> briHotelOrderWrapper = new EntityWrapper<>();
            briHotelOrderWrapper.where("order_no={0}", orderNo);
            List<BriHotelOrder> briHoteltOrders = briHotelOrderService.selectList(briHotelOrderWrapper);
            if (briHoteltOrders != null && briHoteltOrders.size() > 0) {
                if ("1".equals(briHoteltOrders.get(0).getIsNote())) {
                    return;
                }
                briHotelOrderService.delete(briHotelOrderWrapper);
                briHotelOrderService.insert(hotelOrderByJSON);
            } else {
                briHotelOrderService.insert(hotelOrderByJSON);
            }
            //酒店房间及入住人信息
            Wrapper<BriHotelRoom> briHotelRoomWrapperWrapper = new EntityWrapper<>();
            briHotelRoomWrapperWrapper.where("order_no={0}", orderNo);
            briHotelRoomService.delete(briHotelRoomWrapperWrapper);
            List<BriHotelRoom> briHotelRooms = null;
            briHotelRooms = OrderCenterConvert.getBriHotelRoomByJSON(orderJson, orderNo);
            if (briHotelRooms != null && briHotelRooms.size() > 0) {
                briHotelRoomService.insertBatch(briHotelRooms);
            }
            // end 存储酒店房间及入住人信息
        }
    }

    private void dealWithApplyHotel(String tenant, BriHotelOrder hotelOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(hotelOrderByJSON.getRelateYBZID())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(hotelOrderByJSON.getRelateYBZID());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            dealHotelWithSQ(hotelOrderByJSON, heads, !CollectionUtils.isEmpty(heads));
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    private void dealHotelWithSQ(BriHotelOrder hotelOrderByJSON, JSONArray heads, boolean b) {
        if (b) {
            for (Object head : heads) {
                JSONObject headJsonObject = (JSONObject) head;
                if (BriHotelOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        hotelOrderByJSON.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        hotelOrderByJSON.setAssumeOrg(headJsonObject.getString("source_value"));
                    }
                }
                if (BriHotelOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        hotelOrderByJSON.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        hotelOrderByJSON.setAssumeDept(headJsonObject.getString("source_value"));
                    }
                }
                if (BriHotelOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        hotelOrderByJSON.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        hotelOrderByJSON.setCostProject(headJsonObject.getString("source_value"));
                    }
                }
                if (BriHotelOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof JSONObject) {
                        hotelOrderByJSON.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                    } else if (headJsonObject.get("source_value") instanceof String) {
                        hotelOrderByJSON.setApplyUser(headJsonObject.getString("source_value"));
                    }
                }
                if (BriHotelOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                    if (headJsonObject.get("source_value") instanceof String) {
                        hotelOrderByJSON.setCompanion(headJsonObject.getString("source_value"));
                    }
                }
            }
        }
    }

    /**
     * 机票获取选项的参照
     *
     * @param params
     * @return
     */
    public Map getMenuOptions(Map params) {
        Map result = new HashMap();
        String option = params.get("key").toString();
        String type = params.get("type").toString();
        Object tempResult = null;
        switch (option) {
            case "fromType":
                tempResult = getFromTypeOptions(type);
                break;
            case "orderStatus":
                tempResult = getOrderStatusOptions(type);
                break;
            case "payType":
                tempResult = getPayTypeOptions(type);
                break;
            case "paymentType":
                tempResult = getPaymentTypeOptions(type);
                break;
            case "isDomc":
                tempResult = getIsDomcOptions(type);
                break;
            case "hotelType":
                tempResult = getHotelTypeOptions(type);
                break;
            case "bxStatus":
                tempResult = getBxStatusOptions();
                break;
            case "abNormalOrder":
                tempResult = getAbNormalOrderOptions();
                break;
            case "all":
                tempResult = getAllOptions(type);
            default:
                break;
        }
        result.put("code", "0");
        result.put("information", tempResult);
        return result;
    }

    private JSONArray getAbNormalOrderOptions() {
        JSONArray jsonArray = new JSONArray();
        JSONObject j1 = new JSONObject();
        j1.put("value", "all");
        j1.put("label", "全部");
        jsonArray.add(j1);
        JSONObject j2 = new JSONObject();
        j2.put("value", "0");
        j2.put("label", "否");
        jsonArray.add(j2);
        JSONObject j3 = new JSONObject();
        j3.put("value", "1");
        j3.put("label", "是");
        jsonArray.add(j3);
        return jsonArray;
    }

    private JSONArray getHotelTypeOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        JSONObject j1 = new JSONObject();
        j1.put("value", "all");
        j1.put("label", "全部");
        jsonArray.add(j1);
        return jsonArray;
    }


    private JSONArray getFromTypeOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        if ("flight".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "rtpnr");
            j2.put("label", "友商旅");
            jsonArray.add(j2);
            JSONObject j4 = new JSONObject();
            j4.put("value", "clyh");
            j4.put("label", "差旅壹号");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "tuniu");
            j5.put("label", "途牛");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "ctripBC");
            j6.put("label", "携程大客户");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "ctripSME");
            j7.put("label", "携程商旅通");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "zteitc");
            j8.put("label", "中兴");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "fanscar");
            j9.put("label", "泛嘉国际");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "meiya");
            j10.put("label", "美亚");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "HCHoliday");
            j11.put("label", "花城");
            jsonArray.add(j11);
        } else if ("hotel".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "rtpnr");
            j2.put("label", "友商旅");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "ctripBC");
            j3.put("label", "携程大客户");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "clyh");
            j4.put("label", "差旅壹号");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "tujia");
            j5.put("label", "途家");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "tuniu");
            j6.put("label", "途牛");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "ctripSME");
            j7.put("label", "携程商旅通");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "zteitc");
            j8.put("label", "中兴");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "fanscar");
            j9.put("label", "泛嘉国际");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "meiya");
            j10.put("label", "美亚");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "HCHoliday");
            j11.put("label", "花城");
            jsonArray.add(j11);
        } else if ("train".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "rtpnr");
            j2.put("label", "友商旅");
            jsonArray.add(j2);
            JSONObject j4 = new JSONObject();
            j4.put("value", "clyh");
            j4.put("label", "差旅壹号");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "tuniu");
            j5.put("label", "途牛");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "ctripBC");
            j6.put("label", "携程大客户");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "ctripSME");
            j7.put("label", "携程商旅通");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "zteitc");
            j8.put("label", "中兴");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "fanscar");
            j9.put("label", "泛嘉国际");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "meiya");
            j10.put("label", "美亚");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "HCHoliday");
            j11.put("label", "花城");
            jsonArray.add(j11);
        } else if ("car".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "rtpnr");
            j2.put("label", "友商旅");
            jsonArray.add(j2);
            JSONObject j6 = new JSONObject();
            j6.put("value", "ctripBC");
            j6.put("label", "携程大客户");
            jsonArray.add(j6);
            JSONObject j10 = new JSONObject();
            j10.put("value", "didi");
            j10.put("label", "滴滴");
            jsonArray.add(j10);
        }
        return jsonArray;
    }

    private JSONArray getOrderStatusOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        if ("flight".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "WS");
            j2.put("label", "待提交");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "WQ");
            j3.put("label", "待确认");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "WA");
            j4.put("label", "等待审批");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "WR");
            j5.put("label", "审批已拒绝");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "NW");
            j6.put("label", "未支付");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "WP");
            j7.put("label", "待出票");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "NP");
            j8.put("label", "出票完成");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "NR");
            j9.put("label", "退回");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "WC");
            j10.put("label", "未处理");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "CL");
            j11.put("label", "处理中");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "QX");
            j12.put("label", "已取消");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "QT");
            j13.put("label", "全部退票");
            jsonArray.add(j13);
            JSONObject j14 = new JSONObject();
            j14.put("value", "BT");
            j14.put("label", "部分退票");
            jsonArray.add(j14);
            JSONObject j15 = new JSONObject();
            j15.put("value", "CJ");
            j15.put("label", "已成交");
            jsonArray.add(j15);
            JSONObject j16 = new JSONObject();
            j16.put("value", "TI");
            j16.put("label", "退票处理中");
            jsonArray.add(j16);
            JSONObject j17 = new JSONObject();
            j17.put("value", "TP");
            j17.put("label", "退票完成");
            jsonArray.add(j17);
            JSONObject j18 = new JSONObject();
            j18.put("value", "HP");
            j18.put("label", "有退票");
            jsonArray.add(j18);
            JSONObject j19 = new JSONObject();
            j19.put("value", "TE");
            j19.put("label", "异常状态");
            jsonArray.add(j19);

        } else if ("hotel".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "WS");
            j2.put("label", "待提交");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "WQ");
            j3.put("label", "待确认");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "WA");
            j4.put("label", "等待审批");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "WR");
            j5.put("label", "审批已拒绝");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "10");
            j6.put("label", "待确认");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "11");
            j7.put("label", "取消");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "12");
            j8.put("label", "已确认(现付)/待支付(预付)");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "13");
            j9.put("label", "入住中");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "14");
            j10.put("label", "正常离店");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "15");
            j11.put("label", "提前离店");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "16");
            j12.put("label", "NoShow");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "17");
            j13.put("label", "已支付");
            jsonArray.add(j13);
            JSONObject j14 = new JSONObject();
            j14.put("value", "18");
            j14.put("label", "变更取消");
            jsonArray.add(j14);
            JSONObject j15 = new JSONObject();
            j15.put("value", "19");
            j15.put("label", "确认失败已退款");
            jsonArray.add(j15);
            JSONObject j16 = new JSONObject();
            j16.put("value", "20");
            j16.put("label", "已确认(预付)");
            jsonArray.add(j16);
            JSONObject j17 = new JSONObject();
            j17.put("value", "25");
            j17.put("label", "已成交");
            jsonArray.add(j17);
            JSONObject j18 = new JSONObject();
            j18.put("value", "26");
            j18.put("label", "未提交");
            jsonArray.add(j18);
        } else if ("train".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "WS");
            j2.put("label", "待提交");
            jsonArray.add(j2);
            JSONObject j4 = new JSONObject();
            j4.put("value", "WA");
            j4.put("label", "等待审批");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "WR");
            j5.put("label", "审批已拒绝");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "AT");
            j6.put("label", "新单待确认");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "NW");
            j7.put("label", "新订单待支付");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "PY");
            j8.put("label", "已支付");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "TP");
            j9.put("label", "已出票");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "RW");
            j10.put("label", "出票失败待退款");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "RP");
            j11.put("label", "出票失败已退款");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "CO");
            j12.put("label", "已取消");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "AR");
            j13.put("label", "申请退票");
            jsonArray.add(j13);
            JSONObject j14 = new JSONObject();
            j14.put("value", "PR");
            j14.put("label", "退票(退款)部分成功");
            jsonArray.add(j14);
            JSONObject j15 = new JSONObject();
            j15.put("value", "FR");
            j15.put("label", "退票成功");
            jsonArray.add(j15);
            JSONObject j16 = new JSONObject();
            j16.put("value", "RR");
            j16.put("label", "退票失败");
            jsonArray.add(j16);
            JSONObject j17 = new JSONObject();
            j17.put("value", "GA");
            j17.put("label", "改签申请");
            jsonArray.add(j17);
            JSONObject j18 = new JSONObject();
            j18.put("value", "GE");
            j18.put("label", "改签失败");
            jsonArray.add(j18);
            JSONObject j19 = new JSONObject();
            j19.put("value", "GK");
            j19.put("label", "座位确认");
            jsonArray.add(j19);
            JSONObject j20 = new JSONObject();
            j20.put("value", "GO");
            j20.put("label", "取消改签");
            jsonArray.add(j20);
            JSONObject j21 = new JSONObject();
            j21.put("value", "GT");
            j21.put("label", "改签成功");
            jsonArray.add(j21);
            JSONObject j22 = new JSONObject();
            j22.put("value", "GR");
            j22.put("label", "改签退票单(未退款)");
            jsonArray.add(j22);
            JSONObject j23 = new JSONObject();
            j23.put("value", "GD");
            j23.put("label", "改签退票单结束(已退款)");
            jsonArray.add(j23);
            JSONObject j24 = new JSONObject();
            j24.put("value", "N");
            j24.put("label", "未提交");
            jsonArray.add(j24);
            JSONObject j25 = new JSONObject();
            j25.put("value", "WP");
            j25.put("label", "待支付");
            jsonArray.add(j25);
            JSONObject j26 = new JSONObject();
            j26.put("value", "PP");
            j26.put("label", "支付处理中");
            jsonArray.add(j26);
            JSONObject j27 = new JSONObject();
            j27.put("value", "PF");
            j27.put("label", "支付失败");
            jsonArray.add(j27);
            JSONObject j28 = new JSONObject();
            j28.put("value", "WU");
            j28.put("label", "待授权");
            jsonArray.add(j28);
            JSONObject j29 = new JSONObject();
            j29.put("value", "UR");
            j29.put("label", "授权失败");
            jsonArray.add(j29);
            JSONObject j30 = new JSONObject();
            j30.put("value", "WT");
            j30.put("label", "待出票");
            jsonArray.add(j30);
            JSONObject j31 = new JSONObject();
            j31.put("value", "TI");
            j31.put("label", "购票中");
            jsonArray.add(j31);
            JSONObject j32 = new JSONObject();
            j32.put("value", "TD");
            j32.put("label", "已购票");
            jsonArray.add(j32);
            JSONObject j33 = new JSONObject();
            j33.put("value", "TF");
            j33.put("label", "出票失败");
            jsonArray.add(j33);
        } else if ("car".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j7 = new JSONObject();
            j7.put("value", "0");
            j7.put("label", "其他");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "1");
            j8.put("label", "待支付（行程未结束）");
            jsonArray.add(j8);
            JSONObject j2 = new JSONObject();
            j2.put("value", "2");
            j2.put("label", "已支付（行程结束）");
            jsonArray.add(j2);
            JSONObject j4 = new JSONObject();
            j4.put("value", "3");
            j4.put("label", "已退款");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "4");
            j5.put("label", "已取消");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "7");
            j6.put("label", "部分退款");
            jsonArray.add(j6);
            JSONObject j9 = new JSONObject();
            j9.put("value", "10");
            j9.put("label", "等待应答");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "11");
            j10.put("label", "已应答/等待接驾");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "12");
            j11.put("label", "司机已到达");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "13");
            j12.put("label", "行程中/正在服务");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "14");
            j13.put("label", "异常结束（已支付）");
            jsonArray.add(j13);
            JSONObject j14 = new JSONObject();
            j14.put("value", "15");
            j14.put("label", "行程结束（未支付）");
            jsonArray.add(j14);
        }
        return jsonArray;
    }

    private JSONArray getPayTypeOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        if ("flight".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "Prepay");
            j2.put("label", "预付");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "Selfpay");
            j3.put("label", "现付");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "Monthlypay");
            j4.put("label", "月结");
            jsonArray.add(j4);
        } else if ("hotel".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "Prepay");
            j2.put("label", "预付");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "Selfpay");
            j3.put("label", "现付");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "Monthlypay");
            j4.put("label", "月结");
            jsonArray.add(j4);
        } else if ("train".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "Prepay");
            j2.put("label", "预付");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "Selfpay");
            j3.put("label", "现付");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "Monthlypay");
            j4.put("label", "月结");
            jsonArray.add(j4);
        } else if ("car".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "Prepay");
            j2.put("label", "预付");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "Selfpay");
            j3.put("label", "现付");
            jsonArray.add(j3);
        }
        return jsonArray;
    }

    private JSONArray getPaymentTypeOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        if ("flight".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "online");
            j2.put("label", "线上");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "underline");
            j3.put("label", "线下");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "CCARD");
            j4.put("label", "信用卡支付");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "CHECK");
            j5.put("label", "支票支付");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "UNPAY");
            j6.put("label", "银联在线支付");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "ACCNT");
            j7.put("label", "公司账户支付");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "PCARD");
            j8.put("label", "手机支付");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "TMPAY");
            j9.put("label", "礼品卡支付");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "CASH");
            j10.put("label", "现金");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "APPAY");
            j11.put("label", "AirPlus支付");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "DQPAY");
            j12.put("label", "储蓄卡快捷");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "ebank");
            j13.put("label", "网银");
            jsonArray.add(j13);
//            JSONObject j14 = new JSONObject();
//            j14.put("value","cash");
//            j14.put("label","现金");
//            jsonArray.add(j14);
            JSONObject j15 = new JSONObject();
            j15.put("value", "ALPAY");
            j15.put("label", "支付宝");
            jsonArray.add(j15);
            JSONObject j16 = new JSONObject();
            j16.put("value", "WSCAN");
            j16.put("label", "微信");
            jsonArray.add(j16);
            JSONObject j17 = new JSONObject();
            j17.put("value", "ABPAY");
            j17.put("label", "农行网银");
            jsonArray.add(j17);
            JSONObject j18 = new JSONObject();
            j18.put("value", "BCPAY");
            j18.put("label", "中行网银");
            jsonArray.add(j18);
            JSONObject j19 = new JSONObject();
            j19.put("value", "CBPAY");
            j19.put("label", "建行网银");
            jsonArray.add(j19);
            JSONObject j20 = new JSONObject();
            j20.put("value", "CMPAY");
            j20.put("label", "招行网银");
            jsonArray.add(j20);
            JSONObject j21 = new JSONObject();
            j21.put("value", "IBPAY");
            j21.put("label", "工行网银");
            jsonArray.add(j21);
            JSONObject j22 = new JSONObject();
            j22.put("value", "PSPAY");
            j22.put("label", "邮储网银");
            jsonArray.add(j22);
            JSONObject j23 = new JSONObject();
            j23.put("value", "PDPAY");
            j23.put("label", "浦发网银");
            jsonArray.add(j23);
            JSONObject j24 = new JSONObject();
            j24.put("value", "CTPAY");
            j24.put("label", "交通网银");
            jsonArray.add(j24);
            JSONObject j25 = new JSONObject();
            j25.put("value", "MAPAY");
            j25.put("label", "手机支付宝");
            jsonArray.add(j25);
            JSONObject j26 = new JSONObject();
            j26.put("value", "QK");
            j26.put("label", "欠款");
            jsonArray.add(j26);
            JSONObject j27 = new JSONObject();
            j27.put("value", "ZH");
            j27.put("label", "账户");
            jsonArray.add(j27);
//            JSONObject j28 = new JSONObject();
//            j28.put("value","XJ");
//            j28.put("label","现金");
//            jsonArray.add(j28);
            JSONObject j29 = new JSONObject();
            j29.put("value", "WZ");
            j29.put("label", "网支");
            jsonArray.add(j29);
        }
        return jsonArray;
    }

    private JSONArray getIsDomcOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        JSONObject j1 = new JSONObject();
        j1.put("value", "all");
        j1.put("label", "全部");
        jsonArray.add(j1);
        JSONObject j2 = new JSONObject();
        j2.put("value", "D");
        j2.put("label", "国内");
        jsonArray.add(j2);
        JSONObject j3 = new JSONObject();
        j3.put("value", "I");
        j3.put("label", "国际");
        jsonArray.add(j3);
        return jsonArray;
    }

    private JSONArray getSeatTypeOptions(String type) {
        JSONArray jsonArray = new JSONArray();
        if ("train".equals(type)) {
            JSONObject j1 = new JSONObject();
            j1.put("value", "all");
            j1.put("label", "全部");
            jsonArray.add(j1);
            JSONObject j2 = new JSONObject();
            j2.put("value", "硬座");
            j2.put("label", "硬座");
            jsonArray.add(j2);
            JSONObject j3 = new JSONObject();
            j3.put("value", "软座");
            j3.put("label", "软座");
            jsonArray.add(j3);
            JSONObject j4 = new JSONObject();
            j4.put("value", "特等座");
            j4.put("label", "特等座");
            jsonArray.add(j4);
            JSONObject j5 = new JSONObject();
            j5.put("value", "一等座");
            j5.put("label", "一等座");
            jsonArray.add(j5);
            JSONObject j6 = new JSONObject();
            j6.put("value", "二等座");
            j6.put("label", "二等座");
            jsonArray.add(j6);
            JSONObject j7 = new JSONObject();
            j7.put("value", "硬卧上");
            j7.put("label", "硬卧上");
            jsonArray.add(j7);
            JSONObject j8 = new JSONObject();
            j8.put("value", "硬卧中");
            j8.put("label", "硬卧中");
            jsonArray.add(j8);
            JSONObject j9 = new JSONObject();
            j9.put("value", "硬卧下");
            j9.put("label", "硬卧下");
            jsonArray.add(j9);
            JSONObject j10 = new JSONObject();
            j10.put("value", "软卧上");
            j10.put("label", "软卧上");
            jsonArray.add(j10);
            JSONObject j11 = new JSONObject();
            j11.put("value", "软卧下");
            j11.put("label", "软卧下");
            jsonArray.add(j11);
            JSONObject j12 = new JSONObject();
            j12.put("value", "高级软包上");
            j12.put("label", "高级软包上");
            jsonArray.add(j12);
            JSONObject j13 = new JSONObject();
            j13.put("value", "高级软包下");
            j13.put("label", "高级软包下");
            jsonArray.add(j13);
            JSONObject j14 = new JSONObject();
            j14.put("value", "商务座");
            j14.put("label", "商务座");
            jsonArray.add(j14);
            JSONObject j15 = new JSONObject();
            j15.put("value", "无座");
            j15.put("label", "无座");
            jsonArray.add(j15);
            JSONObject j16 = new JSONObject();
            j16.put("value", "硬卧");
            j16.put("label", "硬卧");
            jsonArray.add(j16);
            JSONObject j17 = new JSONObject();
            j17.put("value", "软卧");
            j17.put("label", "软卧");
            jsonArray.add(j17);
            JSONObject j18 = new JSONObject();
            j18.put("value", "高级软卧");
            j18.put("label", "高级软卧");
            jsonArray.add(j18);
            JSONObject j19 = new JSONObject();
            j19.put("value", "一等软卧");
            j19.put("label", "一等软卧");
            jsonArray.add(j19);
            JSONObject j20 = new JSONObject();
            j20.put("value", "二等软卧");
            j20.put("label", "二等软卧");
            jsonArray.add(j20);
            JSONObject j21 = new JSONObject();
            j21.put("value", "一人软包");
            j21.put("label", "一人软包");
            jsonArray.add(j21);
            JSONObject j22 = new JSONObject();
            j22.put("value", "动卧");
            j22.put("label", "动卧");
            jsonArray.add(j22);
            JSONObject j23 = new JSONObject();
            j23.put("value", "动卧上");
            j23.put("label", "动卧上");
            jsonArray.add(j23);
            JSONObject j24 = new JSONObject();
            j24.put("value", "动卧下");
            j24.put("label", "动卧下");
            jsonArray.add(j24);
            JSONObject j25 = new JSONObject();
            j25.put("value", "高级动卧");
            j25.put("label", "高级动卧");
            jsonArray.add(j25);
            JSONObject j26 = new JSONObject();
            j26.put("value", "高级动卧上");
            j26.put("label", "高级动卧上");
            jsonArray.add(j26);
            JSONObject j27 = new JSONObject();
            j27.put("value", "高级动卧下");
            j27.put("label", "高级动卧下");
            jsonArray.add(j27);
            JSONObject j28 = new JSONObject();
            j28.put("value", "其他");
            j28.put("label", "其他");
            jsonArray.add(j28);
        }
        return jsonArray;
    }

    private JSONArray getBxStatusOptions() {
        JSONArray jsonArray = new JSONArray();
        JSONObject j1 = new JSONObject();
        j1.put("value", "all");
        j1.put("label", "全部");
        jsonArray.add(j1);
        JSONObject j2 = new JSONObject();
        j2.put("value", "0");
        j2.put("label", "未报销");
        jsonArray.add(j2);
        JSONObject j3 = new JSONObject();
        j3.put("value", "1");
        j3.put("label", "报销中");
        jsonArray.add(j3);
        JSONObject j4 = new JSONObject();
        j4.put("value", "2");
        j4.put("label", "已报销");
        jsonArray.add(j4);
        return jsonArray;
    }

    private JSONObject getAllOptions(String type) {
        JSONObject jsonObject = new JSONObject();
        if ("flight".equals(type)) {
            jsonObject.put("fromType", getFromTypeOptions(type));
            jsonObject.put("orderStatus", getOrderStatusOptions(type));
            jsonObject.put("payType", getPayTypeOptions(type));
            jsonObject.put("paymentType", getPaymentTypeOptions(type));
            jsonObject.put("isDomc", getIsDomcOptions(type));
            jsonObject.put("bxStatus", getBxStatusOptions());
            jsonObject.put("abNormalOrder", getAbNormalOrderOptions());
        } else if ("hotel".equals(type)) {
            jsonObject.put("fromType", getFromTypeOptions(type));
            jsonObject.put("orderStatus", getOrderStatusOptions(type));
            jsonObject.put("payType", getPayTypeOptions(type));
            jsonObject.put("hotelType", getHotelTypeOptions(type));
            jsonObject.put("bxStatus", getBxStatusOptions());
            jsonObject.put("abNormalOrder", getAbNormalOrderOptions());
        } else if ("train".equals(type)) {
            jsonObject.put("fromType", getFromTypeOptions(type));
            jsonObject.put("orderStatus", getOrderStatusOptions(type));
            jsonObject.put("payType", getPayTypeOptions(type));
            jsonObject.put("seatType", getSeatTypeOptions(type));
            jsonObject.put("bxStatus", getBxStatusOptions());
            jsonObject.put("abNormalOrder", getAbNormalOrderOptions());
        } else if ("car".equals(type)) {
            jsonObject.put("fromType", getFromTypeOptions(type));
            jsonObject.put("orderStatus", getOrderStatusOptions(type));
            jsonObject.put("payType", getPayTypeOptions(type));
            jsonObject.put("bxStatus", getBxStatusOptions());
            jsonObject.put("abNormalOrder", getAbNormalOrderOptions());
        }
        return jsonObject;
    }


}
